package com.term.domain.common;

import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by chenGang on 2017/1/5.
 */
public class ConditionSet extends Condition {

    List<Condition> conditions = new ArrayList<>();


    /**
     * 添加一个条件
     * @param field 查询接口调用者使用的字段
     * @param value 值
     * @return
     */
    public ConditionSet addCondition(String field, Object value){
        return this.addCondition(field, value, MatchType.eq);
    }

    /**
     * 添加一个条件
     * @param field
     * @param value
     * @param matchType 匹配类型， 见Condition.MatchType
     * @return
     */
    public ConditionSet addCondition(String field, Object value, Condition.MatchType matchType){
        if (field == null || value == null)
            return this;

        Condition condition = new Condition(field, value, matchType);
        this.addCondition(condition);
        return this;
    }

    /**
     * 添加一个条件集合
     * 在逻辑与中嵌套逻辑或，或者相反
     * @param condition
     * @return
     */
    public ConditionSet addCondition(Condition condition) {
        conditions.add(condition);
        return this;
    }

    /**
     * 设置一个javax.persistence.Query的参数
     * @param query
     * @param paramIdx 一般情况下都传 1
     * @return 返回修改后的paramIdx
     */
    public int setParameter(Query query, int paramIdx) {
        for (Condition condition : conditions) {
            paramIdx = condition.setParameter(query, paramIdx);
        }
        return paramIdx;
    }

    public boolean isEmpty() {
        return conditions.isEmpty();
    }



}
